package com.controller;

import com.dao.IRevertDAO;
import com.vo.Revert;
import com.vo.Students;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;

@Controller
@RequestMapping("/reverts")
public class RevertController {
    @Autowired
    private IRevertDAO revertDAO;

    @PostMapping
    public String addRevert(@ModelAttribute("newRevert") Revert revert,
                            HttpSession session,
                            RedirectAttributes redirectAttrs) {

        // 设置回复信息
        Students user = (Students) session.getAttribute("currentUser");
        revert.setWriter(user.getStudentName());
        revert.setWriteDate(new Date());

        // 保存回复
        revertDAO.addRevert(revert);

        // 添加重定向参数
        redirectAttrs.addAttribute("id", revert.getMessageID());
        return "redirect:/messages/{id}"; // 确保重定向回原留言页
    }

    @PostMapping("/{id}/delete")
    public String deleteRevert(@PathVariable int id, HttpSession session) {
        Students user = (Students) session.getAttribute("currentUser");
        Revert revert = revertDAO.getRevertById(id);

        if (revert != null && revert.getWriter().equals(user.getStudentName())) {
            int messageId = revert.getMessageID();
            revertDAO.deleteRevert(id);
            return "redirect:/messages/" + messageId;
        }
        return "redirect:/messages";
    }
}